//
//  WBNewFeatureView.swift
//  WinsonWeibo
//
//  Created by Administrator on 2017/4/24.
//  Copyright © 2017年 Winson. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterButton: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!

    /// 进入微博
    @IBAction func enterstauts(_ sender: Any) {
        removeFromSuperview()
    }

    class func newFeatureView() -> WBNewFeatureView {

        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView

        v.frame = UIScreen.main.bounds

        return v
    }

    override func awakeFromNib() {
        // 如果使用自动布局设置的界面，从 XIB 加载默认是 600 * 600 大小
        // 添加 4 个默认视图

        let count = 4
        let rect = UIScreen.main.bounds

        for i in 0..<count {
            let imageView = UIImageView(image: UIImage(named: "new_feature_\(i + 1)"))
            imageView.frame = rect.offsetBy(dx: rect.width * CGFloat(i), dy: 0)
            scrollView.addSubview(imageView)
        }
        // 指定scrollView的属性
        scrollView.contentSize = CGSize(width: rect.width * CGFloat(count + 1), height: rect.height)
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.delegate = self

        enterButton.isHidden = true
    }
}

extension WBNewFeatureView: UIScrollViewDelegate {

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 1. 滚动到最后一屏， 让视图删除
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)

        // 2. 判断是否是最后一页
        if page == scrollView.subviews.count {
            print("欢迎欢迎，热烈欢迎！")
            removeFromSuperview()
        }

        // 3. 如果是倒数第2页，显示按钮
        enterButton.isHidden = (page != scrollView.subviews.count - 1)
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        // 1. 一旦滚动隐藏按钮
        enterButton.isHidden = true

        // 2. 计算当前的偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)

        // 3.设置分控件
        pageControl.currentPage = page

        // 4. 分页控件的隐藏
        pageControl.isHidden = (page == scrollView.subviews.count) ? true : false
    }
}
